package com.smec.moblie.fragment;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;

import com.smec.moblie.R;
import com.smec.moblie.activity.TechnicalNoticeDetailActivity;
import com.smec.moblie.adapter.TechnicalNoticeAllListAdapter;
import com.smec.moblie.adapter.TechnicalNoticeCustomerListAdapter;
import com.smec.moblie.adapter.TechnicalNoticeTechHeadListAdapter;
import com.smec.moblie.bean.CustomersBean;
import com.smec.moblie.bean.TechHeadBean;
import com.smec.moblie.bean.TechnicalNoticeBean;
import com.smec.moblie.control.EventCenter;
import com.smec.moblie.control.MainControl;
import com.smec.moblie.view.listView.MyListView;
import com.smec.moblie.widget.MntjobExpandableListView;

import org.litepal.crud.DataSupport;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;

/**
 * Created by sunyubo on 2017/12/21.
 */

public class TechnicalNoticeFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener {

    @BindView(R.id.imageview_back)
    ImageView imageviewBack;
    @BindView(R.id.imageViewClassification)
    ImageView imageViewClassification;
    @BindView(R.id.rl_title)
    RelativeLayout rlTitle;
    @BindView(R.id.editTextSearch)
    EditText editTextSearch;
    @BindView(R.id.imageViewSelectSequence)
    ImageView imageViewSelectSequence;
    @BindView(R.id.MEListViewTechnicalNotice)
    MntjobExpandableListView mEListViewTechnicalNotice;
    @BindView(R.id.listViewAll)
    MyListView listViewAll;
    @BindView(R.id.scrollViewBy)
    ScrollView scrollViewBy;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    @BindView(R.id.layout_search)
    RelativeLayout layoutSearch;

    private PopupWindow popupWindow;
    //    private boolean isASC;
    private String selectType;
    private String orderType;
    private String searchString = "";
    private String orderStatus = "";
    private boolean isNeedRefesh = false;

    private TechnicalNoticeTechHeadListAdapter technicalNoticeTechHeadListAdapter;
    private TechnicalNoticeCustomerListAdapter technicalNoticeCustomerListAdapter;
    private TechnicalNoticeAllListAdapter technicalNoticeAllListAdapter;
    private Unbinder unbinder;

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.remes_act_technical_notice, container, false);
        unbinder=ButterKnife.bind(this, view);
        if (getArguments().getBoolean("isCompleted", false)) {
            orderStatus = COMPLETED;
        } else {
            orderStatus = UNCOMPLETED;
        }

        initView();
        getData();

        return view;
    }

    private void initView() {
        EventBus.getDefault().register(this);//注册EventBus
        imageviewBack.setOnClickListener(this);
        imageViewClassification.setOnClickListener(this);
        imageViewSelectSequence.setOnClickListener(this);
        LayoutInflater inflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.pop_bubble, null);
        popupWindow = new PopupWindow(contentview, LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setOutsideTouchable(true);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 1f;
                getActivity().getWindow().setAttributes(lp);
            }
        });

        TextView textViewAll = (TextView) contentview.findViewById(R.id.textViewAll);
        TextView textViewByCustomer = (TextView) contentview.findViewById(R.id.textViewByCustomer);
        TextView textViewByNo = (TextView) contentview.findViewById(R.id.textViewByNo);
        textViewAll.setOnClickListener(this);
        textViewByCustomer.setOnClickListener(this);
        textViewByNo.setOnClickListener(this);

        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setColorSchemeColors(Color.GREEN, Color.BLUE, Color.YELLOW);
        refreshLayout.setDistanceToTriggerSync(400);

        selectType = ALL;
        mEListViewTechnicalNotice.setGroupIndicator(null);
        orderType = "asc";

        editTextSearch.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchString = s.toString();
                setData();
            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
    }

    private void getData() {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(true);
            }
        });
        String type = "";
        if (orderStatus.equals(UNCOMPLETED)) {
            type = "TASK";
        } else {
            type = "HISTORY";
        }
        MainControl.getTechnicalNoticeList(type, "", getActivity());
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.imageViewSelectSequence:
                if (orderType.equals("asc")) {
                    imageViewSelectSequence.setImageResource(R.mipmap.image_desc);
                    orderType = "desc";
                    setData();
                } else {
                    imageViewSelectSequence.setImageResource(R.mipmap.image_asc);
                    orderType = "asc";
                    setData();
                }
                break;
            case R.id.imageViewClassification:
                popupWindow.showAsDropDown(imageViewClassification, -138, 0);
                WindowManager.LayoutParams lp = getActivity().getWindow().getAttributes();
                lp.alpha = 0.7f;
                getActivity().getWindow().setAttributes(lp);
                break;
            case R.id.textViewAll:
                Toast.makeText(getActivity(), "选择了全部", Toast.LENGTH_SHORT).show();
                selectType = ALL;
                setData();
                popupWindow.dismiss();
                break;
            case R.id.textViewByCustomer:
                Toast.makeText(getActivity(), "选择了按客户归类", Toast.LENGTH_SHORT).show();
                selectType = BYCUSTOMER;
                setData();
                popupWindow.dismiss();
                break;
            case R.id.textViewByNo:
                Toast.makeText(getActivity(), "选择了按编号归类", Toast.LENGTH_SHORT).show();
                selectType = BYNO;
                setData();
                popupWindow.dismiss();
                break;

        }
    }

    /**
     * 获取技术通知单列表数据成功数据处理
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.TechnicalNoticeListBackSuccess event) {
        isNeedRefesh = false;
        setData();
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(false);
            }
        });
    }

    private void setData() {
        String limtString = "%" + searchString + "%";
        if (BYNO.equals(selectType)) {
            listViewAll.setVisibility(View.GONE);
            mEListViewTechnicalNotice.setVisibility(View.VISIBLE);
            List<TechHeadBean> techHeadBeanList = DataSupport.findAll(TechHeadBean.class);
            for (TechHeadBean techHeadBean : techHeadBeanList) {
                List<TechnicalNoticeBean> technicalNoticeBeanList = DataSupport.where("noticeId = ? AND status = ? AND (requireCompleteDate like ? OR customerName like ? OR address like ? OR noticeNum like ? OR eleContractNo like ? OR eleType like ? OR eleNo like ?)", techHeadBean.getNoticeId() + "", orderStatus, limtString, limtString, limtString, limtString, limtString, limtString, limtString).order("requireCompleteDate " + orderType).find(TechnicalNoticeBean.class);
                techHeadBean.setList(technicalNoticeBeanList);
            }
            technicalNoticeTechHeadListAdapter = new TechnicalNoticeTechHeadListAdapter(getActivity());
            technicalNoticeTechHeadListAdapter.setTechnicalNoticeList(techHeadBeanList);
            mEListViewTechnicalNotice.setAdapter(technicalNoticeTechHeadListAdapter);
            mEListViewTechnicalNotice.setOnChildClickListener(new MyOnChildClickListener());
        } else if (BYCUSTOMER.equals(selectType)) {
            listViewAll.setVisibility(View.GONE);
            mEListViewTechnicalNotice.setVisibility(View.VISIBLE);
            List<CustomersBean> customersBeanList = DataSupport.findAll(CustomersBean.class);
            for (CustomersBean customersBean : customersBeanList) {
                List<TechnicalNoticeBean> technicalNoticeBeanList = DataSupport.where("customerId = ? AND status = ? AND (requireCompleteDate like ? OR customerName like ? OR address like ? OR noticeNum like ? OR eleContractNo like ? OR eleType like ? OR eleNo like ?)", customersBean.getCustomerId() + "", orderStatus, limtString, limtString, limtString, limtString, limtString, limtString, limtString).order("requireCompleteDate " + orderType).find(TechnicalNoticeBean.class);
                customersBean.setList(technicalNoticeBeanList);
            }
            technicalNoticeCustomerListAdapter = new TechnicalNoticeCustomerListAdapter(getActivity());
            technicalNoticeCustomerListAdapter.setTechnicalNoticeList(customersBeanList);
            mEListViewTechnicalNotice.setAdapter(technicalNoticeCustomerListAdapter);
            mEListViewTechnicalNotice.setOnChildClickListener(new MyOnChildClickListener());
        } else {
            listViewAll.setVisibility(View.VISIBLE);
            mEListViewTechnicalNotice.setVisibility(View.GONE);
            technicalNoticeAllListAdapter = new TechnicalNoticeAllListAdapter(getActivity());
            listViewAll.setAdapter(technicalNoticeAllListAdapter);
            technicalNoticeAllListAdapter.setList(DataSupport.where("  status = ? AND (requireCompleteDate like ? OR customerName like ? OR address like ? OR noticeNum like ? OR eleContractNo like ? OR eleType like ? OR eleNo like ?)", orderStatus, limtString, limtString, limtString, limtString, limtString, limtString, limtString).order("requireCompleteDate " + orderType).find(TechnicalNoticeBean.class));
            listViewAll.setOnItemClickListener(new MyOnItemClickListener());
        }

        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                refreshLayout.setRefreshing(false);
            }
        });
    }

    @Override
    public void onRefresh() {
        isNeedRefesh = true;
        getData();
    }

    /**
     * 展开项点击事件
     */
    private class MyOnChildClickListener implements ExpandableListView.OnChildClickListener {


        @Override
        public boolean onChildClick(ExpandableListView parent, View v, final int groupPosition, final int childPosition, long id) {
            if (BYNO.equals(selectType)) {
                startDetailActivity(technicalNoticeTechHeadListAdapter.getChild(groupPosition, childPosition));
            } else {
                startDetailActivity(technicalNoticeCustomerListAdapter.getChild(groupPosition, childPosition));
            }
            return false;
        }
    }

    /**
     * 列表项点击事件
     */
    private class MyOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            startDetailActivity(technicalNoticeAllListAdapter.getItem(position));
        }
    }

    private void startDetailActivity(TechnicalNoticeBean technicalNoticeBean) {
        Intent intent = new Intent(getActivity(), TechnicalNoticeDetailActivity.class);
        intent.putExtra("technicalNoticeBean", technicalNoticeBean);
        startActivity(intent);
    }

    /**
     * 获取技术通知单列表数据失败数据处理
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.TechnicalNoticeListBackFailed event) {
        Toast.makeText(getActivity(), "获取技术通知单失败，原因：" + event.getMsg(), Toast.LENGTH_SHORT).show();
    }

    /**
     * 顶部选择
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.TopSelector event) {
        selectType = event.getType();
        setData();
    }

    /**
     *  刷新本地数据
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.ReflashTechnicalNoticeList event) {
        setData();
    }

    /**
     * 切换list
     **/
    @Subscribe
    public void onEventMainThread(EventCenter.ChangeTechnicalNoticeList event) {
        if (event.getIsCompleted()) {
            orderStatus = COMPLETED;
        } else {
            orderStatus = UNCOMPLETED;
        }
        getData();
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
        // 消息bus解注
        EventBus.getDefault().unregister(this);
    }
}